import requests
import json

def listen_mcp_sse():
    url = "http://localhost:8000/mcp/events"
    headers = {"Accept": "text/event-stream"}

    try:
        response = requests.get(url, stream=True, headers=headers)
        response.raise_for_status()

        print("Connected to MCP SSE Server. Waiting for events...")
        for line in response.iter_lines():
            if line.startswith(b"data:"):
                event_data = json.loads(line.decode().split("data: ")[1])
                print(
                    f"[MCP Event] Device: {event_data['device_id']}, "
                    f"Temp: {event_data['data']['temp']}°C"
                )

    except requests.exceptions.RequestException as e:
        print(f"MCP Connection Error: {e}")
    finally:
        print("Disconnected from MCP server.")

if __name__ == "__main__":
    listen_mcp_sse()